package com.ws.common.util;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;
import org.springframework.util.CollectionUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by WS on 2018/1/25.
 */
public class BeanUtils {

    public BeanUtils() {
    }

    public static <T> T copyBean(Object o, Class<T> i) {
        BeanCopier copy = BeanCopier.create(o.getClass(), i, false);
        Object t = null;

        try {
            t = i.newInstance();
        } catch (InstantiationException var5) {
            var5.printStackTrace();
        } catch (IllegalAccessException var6) {
            var6.printStackTrace();
        }

        copy.copy(o, t, (Converter)null);
        return (T) t;
    }

    public static <T> List<T> copyListBean(List<?> list, Class<T> clazz) {
        return CollectionUtils.isEmpty(list)?null:(List)list.stream().map((c) -> {
            return copyBean(c, clazz);
        }).collect(Collectors.toList());
    }


    public static Object convertMap(Class type, Map map) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            Object obj = type.newInstance();
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for(int i = 0; i < propertyDescriptors.length; ++i) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if(map.containsKey(propertyName)) {
                    Object value = map.get(propertyName);
                    Object[] args = new Object[]{value};
                    descriptor.getWriteMethod().invoke(obj, args);
                }
            }

            return obj;
        } catch (Exception var10) {
            var10.getMessage();
            return null;
        }
    }


}
